﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

/// <summary>
///Utils 的摘要说明
/// </summary>
public class Utils
{
	public Utils()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    /// <summary>
    /// 返回工程当前的目录
    /// </summary>
    /// <returns></returns>
    public static string getCurrentDirectory()
    {
        return System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="control">网页中的FileUpload控件的引用</param>
    /// <param name="rootDirectory">上传的目录</param>
    /// <returns></returns>
    public static string uploadFile(FileUpload control,string rootDirectory)
    {
        bool fileOK = false;
        if (control.HasFile)
        {
            string fileExtension = System.IO.Path.GetExtension(control.FileName).ToLower();
            string[] allowedExtensions = new string[] { ".gif", ".png", ".bmp", ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; ++i)
            {
                if (fileExtension.Equals(allowedExtensions[i]))
                {
                    fileOK = true;
                }
            }
        }

        if (fileOK)
        {
            string fileName = "";
            string extension = "";
            try
            {
                fileName += (long)(DateTime.Now.Subtract(DateTime.Parse("1970-1-1")).TotalMilliseconds);
                extension = System.IO.Path.GetExtension(control.FileName).ToLower();
                control.SaveAs(rootDirectory+fileName + extension);

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return fileName + extension;
        }
        return null;
    }

    /// <summary>
    /// 用户修改产品时可能会改变图片，此方法用来替换原来的旧图片
    /// </summary>
    /// <param name="control">Web控件FileUpload</param>
    /// <returns></returns>
    public static string replaceFile(FileUpload control,string oldFileName)
    {
        string newFileName = uploadFile(control,getCurrentDirectory()+"\\pimages\\");
        File.Delete(getCurrentDirectory()+"\\pimages\\"+oldFileName);
        return newFileName;
    }
}
